package com.niiwoo.civet.mobile.controller.creditloan;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.niiwoo.civet.account.dto.request.BillQueryRequest;
import com.niiwoo.civet.account.dto.response.NiiwooUserBillResponseDTO;
import com.niiwoo.civet.account.enums.*;
import com.niiwoo.civet.account.service.MoneyTotalDubboService;
import com.niiwoo.civet.account.service.NiiwooBillDubboService;
import com.niiwoo.civet.mobile.vo.request.credit.QueryCreditContractRequestVO;
import com.niiwoo.civet.mobile.vo.request.credit.QueryCreditRepaymentDynamicRequestVO;
import com.niiwoo.civet.mobile.vo.response.credit.*;
import com.niiwoo.civet.mobile.vo.response.creditloan.INeedGuaranteeResponseVO;
import com.niiwoo.civet.mobile.vo.response.loan.credit.CreditLoanGuaranteeProject;
import com.niiwoo.civet.mobile.vo.response.loan.credit.history.MyCreditLoanResponseVO;
import com.niiwoo.civet.trade.dto.request.credit.*;
import com.niiwoo.civet.trade.dto.request.creditloan.MyCreditLoanRequestDTO;
import com.niiwoo.civet.trade.dto.request.loan.credit.INeedGuaranteeRequestDTO;
import com.niiwoo.civet.trade.dto.response.MyCreditLoanResponseDTO;
import com.niiwoo.civet.trade.dto.response.credit.*;
import com.niiwoo.civet.trade.enums.credit.CreditLoanGuaranteeProjectStatusEnum;
import com.niiwoo.civet.trade.service.credit.CreditDubboService;
import com.niiwoo.civet.trade.service.credit.InvestigationDubboService;
import com.niiwoo.civet.trade.service.loan.credit.CreditLoanDubboService;
import com.niiwoo.tripod.base.utils.DateUtils;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.shiro.UserAuthPrincipal;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.vo.PageRequestVO;
import com.niiwoo.tripod.web.vo.PageResponseVO;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.niiwoo.tripod.web.vo.Result.with;

/**
 * 信用借 Controller
 *
 * @author daizhiyue
 * @author weiliming
 */
@Slf4j
@RestController
@RequestMapping("/creditLoan")
@Api(tags = "信用借", description = "/creditLoan")
public class CreditLoanController {

    @Reference(version = "1.0.0")
    private CreditLoanDubboService creditLoanDubboService;

    @Reference(version = "1.0.0")
    private CreditDubboService creditDubboService;

    @Reference(version = "1.0.0")
    private InvestigationDubboService investigationDubboService;

    @Reference(version = "1.0.0")
    private MoneyTotalDubboService moneyTotalDubboService;

    @Reference(version = "1.0.0")
    private NiiwooBillDubboService niiwooBillDubboService;

    @Value("${credit-loan.guarantee-record-url}")
    private String guaranteeRecordUrl;

    @Value("${credit-loan.invest-record-url}")
    private String investRecordUrl;

    @Value("${credit-loan.borrow-record-url}")
    private String borrowRecordUrl;

    @Value("${credit-loan.invest-contract-url}")
    private String investContractUrl;

    @Value("${credit-loan.guarantee-contract-url}")
    private String guaranteeContractUrl;


    @AuthIgnore
    @PostMapping("/guarantee/iNeed")
    @ApiOperation("我要担保列表(李传志)")
    public Result<PageResponseVO<INeedGuaranteeResponseVO>> pageINeedGuaranteeList(@RequestBody @Valid PageRequestVO pageRequestVO) {
        INeedGuaranteeRequestDTO guaranteeRequestDTO = new INeedGuaranteeRequestDTO();
        guaranteeRequestDTO.setPageNumber(pageRequestVO.getPageNumber());
        guaranteeRequestDTO.setPageSize(pageRequestVO.getPageSize());
        return with(JSON.parseObject(JSON.toJSONString(creditLoanDubboService.pageINeedGuarantee(guaranteeRequestDTO)),
                new TypeReference<PageResponseVO<INeedGuaranteeResponseVO>>() {
                }));
    }


    @PostMapping("/myCreditLoanQuery")
    @ApiOperation("我的借款列表(戴志越)")
    public Result<PageResponseVO<MyCreditLoanResponseVO>> myloanEndedQuery(@RequestBody PageRequestVO vo) {
        String userId = PrincipalContext.getUserId();
        MyCreditLoanRequestDTO dto = new MyCreditLoanRequestDTO();
        dto.setPageNumber(vo.getPageNumber());
        dto.setPageSize(vo.getPageSize());
        dto.setUserId(userId);
        PageResponseDTO<MyCreditLoanResponseDTO> pageDto = creditDubboService.myCreditLoanQuery(dto);
        List<MyCreditLoanResponseVO> voList = JSON.parseArray(JSON.toJSONString(pageDto.getItems()), MyCreditLoanResponseVO.class);
        PageResponseDTO<MyCreditLoanResponseVO> page = new PageResponseDTO<>();
        page.setItems(voList);
        page.setTotalPage(pageDto.getTotalPage());
        page.setTotalCount(pageDto.getTotalCount());
        page.getItems().forEach(p -> {
            if (p.getContractUrl() == null) {
                String h5ContractUrl = investContractUrl + p.getProjectId() + "&type=1";
                p.setContractUrl(h5ContractUrl);
            }
            p.setH5Url(borrowRecordUrl + p.getProjectId());
        });
        return with(JSON.parseObject(JSON.toJSONString(page),
                PageResponseVO.class));
    }


    @PostMapping("/guarantee/mylist")
    @ApiOperation(value = "我的担保列表(魏黎明)")
    public Result<PageResponseVO<CreditLoanGuaranteeProject>> queryMyCreditLoanGuaranteProjectList(@RequestBody PageRequestVO pageRequestVO) {
        UserAuthPrincipal principal = (UserAuthPrincipal) SecurityUtils.getSubject().getPrincipal();
        String userId = principal.getUserId();
        CreditLoanGuaranteeProjectRequestDTO pagetRequestDTO = new CreditLoanGuaranteeProjectRequestDTO();
        pagetRequestDTO.setUserId(userId);
        pagetRequestDTO.setPageNumber(pageRequestVO.getPageNumber());
        pagetRequestDTO.setPageSize(pageRequestVO.getPageSize());
        PageResponseDTO<CreditLoanGuaranteeProjectResponseDTO> projectDTO = creditLoanDubboService.myCreditLoanGuaranteeProjects(pagetRequestDTO);
        if (Objects.isNull(projectDTO) || (projectDTO.getItems().size()) == 0)
            return with(new PageResponseVO<>());
        PageResponseVO<CreditLoanGuaranteeProject> pageResponseVO = new PageResponseVO<>();
        List<CreditLoanGuaranteeProject> list = new ArrayList<>();
        projectDTO.getItems().forEach(dto -> {
            CreditLoanGuaranteeProject project = CreditLoanGuaranteeProject.copyPropertiesFromDTO2VO(dto);
            /*
             * h5合同地址,担保合同查看地址
             */
            if (StringUtils.isEmpty(project.getContractUrl()))
                project.setContractUrl(String.format(guaranteeContractUrl, dto.getProjectId(), 2));// 担保合同type=2

            CreditLoanGuaranteeProject.ViewProjectStatus viewProjectStatus;
            if (Objects.isNull(dto.getProjectStatus())) // 项目的异常状态前端显示状态为[还款中]
                viewProjectStatus = CreditLoanGuaranteeProject.ViewProjectStatus.REPAYMENT;
            else
                viewProjectStatus = adaptSubStatus(dto.getProjectStatus());
            if (Objects.isNull(viewProjectStatus)) {
                log.error("信用借获取项目担保列表异常:项目状态错误!projectId: {}", dto.getProjectId());
                viewProjectStatus = CreditLoanGuaranteeProject.ViewProjectStatus.REPAYMENT;
            }
            project.setViewStatus(viewProjectStatus.getCode());
            project.setTips(viewProjectStatus.getTips());
            // 担保记录查看type=2
            project.setGuaranteeRecordUrl(String.format(guaranteeRecordUrl, dto.getProjectId(), 2, dto.getId()));
            list.add(project);
        });
        pageResponseVO.setTotalCount(projectDTO.getTotalCount());
        pageResponseVO.setTotalPage(projectDTO.getTotalPage());
        pageResponseVO.setItems(list);
        return with(pageResponseVO);
    }

    /**
     * 担保项目子状态转换,页面展示
     *
     * @param i
     * @return
     */
    private CreditLoanGuaranteeProject.ViewProjectStatus adaptSubStatus(byte i) {

        CreditLoanGuaranteeProjectStatusEnum projectStatusEnum = CreditLoanGuaranteeProjectStatusEnum.enumOf(i);
        switch (projectStatusEnum) {
            case LOAN_SUCCESS:
            case YELLOW_WARNING:
            case RED_WARNING:
                return CreditLoanGuaranteeProject.ViewProjectStatus.REPAYMENT;//还款中
            case LOAN:
            case GUARANTEE:
            case GUARANTEE_NOT_PASS:
            case LOAN_FAILURE:
            case LOAN_FAILURE_MANUAL:
                return CreditLoanGuaranteeProject.ViewProjectStatus.MISCARRY;//流标
            case OVERDUE:
            case BAD_DEBT:
                /*
                 * 借款人逾期或者严重逾期时,无论担保人是否垫付逾期都展示(夏永)
                 */
                return CreditLoanGuaranteeProject.ViewProjectStatus.OVERDUE_REPAYMENT;//逾期
            case REPAYMENT_FINISH:
            case BAD_DEBT_REPAYMENT_FINISH:
                return CreditLoanGuaranteeProject.ViewProjectStatus.FINISH;//已结清
            default:
                return null;
        }

    }

    @PostMapping("/guarantee/statistics")
    @ApiOperation(value = "我的担保项目统计信息(魏黎明)")
    public Result<CreditLoanGuaranteeStatisticsResponseVO> queryMyCreditLoanGuaranteeStatistics() {
        UserAuthPrincipal principal = (UserAuthPrincipal) SecurityUtils.getSubject().getPrincipal();
        String userId = principal.getUserId();
        CreditLoanGuaranteeStatisticsResponseVO responseVO = new CreditLoanGuaranteeStatisticsResponseVO();
        if (Objects.isNull(Optional.ofNullable(userId).orElse(null)))
            return with(responseVO);
        CreditLoanGuaranteeStatisticsRequestDTO requestDTO = new CreditLoanGuaranteeStatisticsRequestDTO();
        requestDTO.setUserId(userId);
        CreditLoanGuaranteeStatisticsResponseDTO responseDTO = creditLoanDubboService.creditLoanGuaranteeStatistics(requestDTO);
        if (Objects.isNull(responseDTO)) return with(responseVO);
        // 担保总收益
        BigDecimal totalGuaranteeIncome = moneyTotalDubboService.queryMoneyByUserIdAndAccountType(requestDTO.getUserId(), AccountAmountTypeEnum.GUARANTEE_INCOME);
        responseVO.setTotalGuaranteAmount(responseDTO.getTotalGuaranteeFee());//总担保金额
        responseVO.setTotalGuaranteIncome(totalGuaranteeIncome);//总担保收益
        responseVO.setTotalGuaranteNum(responseDTO.getTotalGuaranteeNum());//总担保笔数
        return with(responseVO);
    }


    @ApiOperation("尽调（贾波）")
    @PostMapping("/investigation/getInvestigationStatistics")
    public Result<InvestigationStatisticsResponseVO> getInvestigationStatistics() {
        String userId = PrincipalContext.getUserId();
        InvestigationStatisticsDTO investigationStatisticsDTO = investigationDubboService.getInvestigationStatistics(userId);
        return with(InvestigationStatisticsResponseVO.convertDTO2VO(investigationStatisticsDTO));
    }

    @ApiOperation("我的尽调（贾波）")
    @PostMapping("/investigation/getInvestigationProjectList")
    public Result<PageResponseVO<InvestigationProjectResponseVO>> getInvestigationProjectList(
            @RequestBody @Valid PageRequestVO requestVO) {

        PageResponseVO<InvestigationProjectResponseVO> pageResponseVO = new PageResponseVO<InvestigationProjectResponseVO>();

        // 请求参数
        GetInvestigationProjectListRequest request = new GetInvestigationProjectListRequest();
        request.setUserId(PrincipalContext.getUserId());
        request.setPageNumber(requestVO.getPageNumber());
        request.setPageSize(requestVO.getPageSize());

        // 调用Dubbo服务获取尽调项目信息
        PageResponseDTO<InvestigationProjectDTO> investigationProjectDTOPage = investigationDubboService.getInvestigationProjectPage(request);

        // 返回结果
        List<InvestigationProjectResponseVO> investigationProjectResponseVOList = Lists.newArrayList();
        if (investigationProjectDTOPage != null) {
            pageResponseVO.setTotalCount(investigationProjectDTOPage.getTotalCount());
            pageResponseVO.setTotalPage(investigationProjectDTOPage.getTotalPage());
            if (CollectionUtils.isNotEmpty(investigationProjectDTOPage.getItems())) {
                for (InvestigationProjectDTO investigationProjectDTO : investigationProjectDTOPage.getItems()) {
                    investigationProjectResponseVOList.add(InvestigationProjectResponseVO.convertDTO2VO(investigationProjectDTO));
                }
                pageResponseVO.setItems(investigationProjectResponseVOList);
            } else {
                pageResponseVO.setItems(Lists.newArrayList());
            }
        }
        return with(pageResponseVO);
    }

    @PostMapping("/invest/creditInvestList")
    @ApiOperation("信用借投资记录(赖春景)")
    public Result<PageResponseVO<CreditInvestListResponseVO>> getCreditInvestmentProjectList(@RequestBody @Valid PageRequestVO pageRequestVO) {

        String userId = PrincipalContext.getUserId();
//        if(Optional.ofNullable(userId).orElse(0L) <= 0L) return with(new PageResponseVO<>());
        CreditLoanInvestProjectRequestDTO requestDTO = new CreditLoanInvestProjectRequestDTO();
        requestDTO.setUserId(userId);
        requestDTO.setPageSize(pageRequestVO.getPageSize());
        requestDTO.setPageNumber(pageRequestVO.getPageNumber());
        PageResponseDTO<QueryCreditInvestInfoReponseDTO> pageResponse = creditDubboService.queryCreditInvestInfoByProjectId(requestDTO);

        List<CreditInvestListResponseVO> resultVo = new ArrayList<>();
        PageResponseVO<CreditInvestListResponseVO> pageResponseVO = new PageResponseVO<>();
        int totalCount = pageResponse.getTotalCount();
        if (pageResponse != null) {
            List<QueryCreditInvestInfoReponseDTO> creditInvestInfoReponseList = pageResponse.getItems();

            for (QueryCreditInvestInfoReponseDTO creditInvestInfoReponseDTO : creditInvestInfoReponseList) {
                CreditInvestListResponseVO items = new CreditInvestListResponseVO();
                items.setProjectId(creditInvestInfoReponseDTO.getProjectId());
                items.setBorrowerUserId(creditInvestInfoReponseDTO.getBorrowerUserId());
                items.setContractAmount(creditInvestInfoReponseDTO.getBorrowAmount());
                items.setBorrowerGender(creditInvestInfoReponseDTO.getBorrowerGender());
                items.setBorrowerHeadImage(creditInvestInfoReponseDTO.getBorrowerHeadImage());
                items.setBorrowerNickName(creditInvestInfoReponseDTO.getBorrowerNickName());
                items.setBorrowRate(creditInvestInfoReponseDTO.getBorrowRate());
                items.setDeadLine(creditInvestInfoReponseDTO.getDeadLine());
                items.setFullSuccessDate(creditInvestInfoReponseDTO.getFullSuccessDate());
                items.setCreateTime(creditInvestInfoReponseDTO.getCreateTime());
                if (creditInvestInfoReponseDTO.getContractUrl() == null) {
                    //投资列表合同type=3
                    String h5OrgContractUrl = investContractUrl + creditInvestInfoReponseDTO.getProjectId() + "&type=3";
                    items.setContractUrl(h5OrgContractUrl);
                } else {
                    items.setContractUrl(creditInvestInfoReponseDTO.getContractUrl());
                }
                items.setInvestedAmount(creditInvestInfoReponseDTO.getInvestedAmount());
                items.setLoanArea(creditInvestInfoReponseDTO.getLoanArea());
                items.setRevenue(creditInvestInfoReponseDTO.getRevenue());
                items.setLoanCity(creditInvestInfoReponseDTO.getLoanCity());
                items.setStatus(creditInvestInfoReponseDTO.getStatus());
                items.setText(creditInvestInfoReponseDTO.getText());
                items.setTitle(creditInvestInfoReponseDTO.getTitle());
                items.setH5Url(investRecordUrl + creditInvestInfoReponseDTO.getProjectId()
                        + "&type=3&opId=" + creditInvestInfoReponseDTO.getId());
                resultVo.add(items);
            }
            pageResponseVO.setTotalPage(pageResponse.getTotalPage());
            pageResponseVO.setTotalCount(totalCount);
            pageResponseVO.setItems(resultVo);

        }
        return with(pageResponseVO);
    }

//    @PostMapping("/queryCreditDynamic")
//    @ApiOperation("查询信用借记录（赖春景）")
//    public Result<QueryCreditRepaymentDynamicReponseVO> queryCreditRepaymentDynamic(
//            @RequestBody @Valid QueryCreditRepaymentDynamicRequestVO requestVO) {
//        String userId = PrincipalContext.getUserId();
//        QueryCreditRepaymentDynamicReponseVO reponseVO = new QueryCreditRepaymentDynamicReponseVO();
//        QueryCreditProjectDynamicReponseDTO dto = creditDubboService.queryCreditProjectDynamic(requestVO.getProjectId(),
//                userId, requestVO.getOpId(), requestVO.getType());
//        if (dto != null) {
//            reponseVO.setProjectId(dto.getProjectId());
//
//            List<QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO> repaymentDynamicVOList = new ArrayList<QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO>();
//            List<CreditProjectDynamicReponseDTO> projectDynamicReponseDTOList = dto.getCreditProjectDynamicReponseDTOSList();
//            if(projectDynamicReponseDTOList != null){
//                for (CreditProjectDynamicReponseDTO projectDynamicReponseDTO : projectDynamicReponseDTOList) {
//                    QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO repaymentDynamicVO = new QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO();
//
//                    BeanUtils.copyProperties(projectDynamicReponseDTO, repaymentDynamicVO);
//                    repaymentDynamicVOList.add(repaymentDynamicVO);
//                }
//            }
//            reponseVO.setCreditRepaymentDynamicVOList(repaymentDynamicVOList);
//
//            reponseVO.setLastDescription(dto.getLastDescription());
//        }
//        return with(reponseVO);
//    }

    @PostMapping("/queryCreditDynamic")
    @ApiOperation("查询信用借记录(肖应平)")
    public Result<QueryCreditRepaymentDynamicReponseVO> queryCreditRepaymentDynamic(@RequestBody @Valid QueryCreditRepaymentDynamicRequestVO request) {
        Long startTime = System.currentTimeMillis();
        log.info("queryCreditRepaymentDynamic start, request:{}", JSON.toJSONString(request));
        String userId = PrincipalContext.getUserId();
        Long projectId = request.getProjectId();

        //查询垫付信息
        CreditLoanGuaranteeProjectDetailRequestDTO creditLoanGuaranteeProjectDetailRequestDTO = new CreditLoanGuaranteeProjectDetailRequestDTO();
        creditLoanGuaranteeProjectDetailRequestDTO.setUserId(userId);
        creditLoanGuaranteeProjectDetailRequestDTO.setProjectId(projectId);
        CreditLoanGuaranteeProjectDetailResponseDTO guarantee = creditLoanDubboService.creditLoanGuaranteeProjectDetail(creditLoanGuaranteeProjectDetailRequestDTO);
        CreditProjectDTO creditProjectDTO = creditDubboService.getCreditProjectById(projectId);

        String lastDescription = "";
        Byte projectStatus = creditProjectDTO.getProjectStatus();
        if (Objects.nonNull(guarantee) && (Byte.valueOf("43").equals(projectStatus) || Byte.valueOf("44").equals(projectStatus))) {
            //已结清的标不需要显示lastDescription
            if (Objects.nonNull(guarantee.getAdvanceAmount()) && Objects.nonNull(guarantee.getRealAdvanceAmount()) && Objects.nonNull(guarantee.getOverdueFine())) {
                BigDecimal balanceAdvanceAmount = guarantee.getAdvanceAmount().subtract(guarantee.getRealAdvanceAmount());
                BigDecimal overdueFine = guarantee.getOverdueFine();
                BigDecimal shouldAdvanceAmount = balanceAdvanceAmount.add(overdueFine);

                StringBuffer sbf = new StringBuffer("借款人还款已逾期，存管上线数据迁移无法再更新数据，请尽快联系客服进行查询或垫付");
                if(shouldAdvanceAmount.compareTo(BigDecimal.ZERO) > 0){
                    sbf.append("。剩余待垫付").append(shouldAdvanceAmount).append("元");
                }
                if(balanceAdvanceAmount.compareTo(BigDecimal.ZERO) > 0){
                    sbf.append("，其中待垫付本金").append(balanceAdvanceAmount).append("元");
                }
                if(overdueFine.compareTo(BigDecimal.ZERO) > 0){
                    sbf.append("，待缴纳滞纳金").append(overdueFine).append("元");
                }
                sbf.append("。");
                lastDescription = sbf.toString();
            }
        }

        //调用账单接口进行查询
        BillQueryRequest billQueryRequest = new BillQueryRequest();
        billQueryRequest.setUserId(userId);
        billQueryRequest.setProjectId(projectId);
        billQueryRequest.setFirstCodeS(Arrays.asList(BillFirstSubjectEnum.USER_GUARANTEE_BACK.getCode(), BillFirstSubjectEnum.USER_GUARANTEE_INCOME.getCode(), BillFirstSubjectEnum.USER_GUARANTEE_REPAYMENT.getCode(),
                BillFirstSubjectEnum.USER_GUARANTEE_PAY_BACK.getCode(), BillFirstSubjectEnum.USER_GUARANTEE_OUTCOME.getCode(), BillFirstSubjectEnum.USER_GUARANTEE_PAY.getCode()));
        billQueryRequest.setIsVisibleEnum(BillIsVisibleEnum.SHOW);
        List<NiiwooUserBillResponseDTO> billResponseDTOList = niiwooBillDubboService.listUserBills(billQueryRequest);

        List<QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO> userBillDetailList = billResponseDTOList.stream().map(userBillResponseDTO -> {
            String secondSubjectCode = userBillResponseDTO.getSecondSubjectCode();
            String billDesc = "";
            if (BillSecondSubjectEnum.USER_GUARANTEE_REPAYMENT.getCode().equals(secondSubjectCode)) {
                billDesc = "项目结束，回款担保保证金";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_PAY_BACK_CORPUS.getCode().equals(secondSubjectCode)) {
                billDesc = "借款人逾期还款，垫付本金回款";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_PAY_BACK_OVERDUE_FEE.getCode().equals(secondSubjectCode)) {
                billDesc = "借款人逾期还款，获得罚息";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_PAY_ADVANCE.getCode().equals(secondSubjectCode) || BillSecondSubjectEnum.USER_GUARANTEE_RECEIVE_GUARANTOR_CORPUS.getCode().equals(secondSubjectCode)) {
                billDesc = "借款人逾期，垫付本金";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_LATE_FEE.getCode().equals(secondSubjectCode)) {
                billDesc = "借款人逾期，未及时垫付，缴纳滞纳金";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_INCOME_FEE.getCode().equals(secondSubjectCode)) {
                billDesc = "借款项目已投资满标，获得尽调费";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_INCOME_BONUS.getCode().equals(secondSubjectCode)) {
                billDesc = "借款项目已投资满标，获得尽调奖励";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_INCOME.getCode().equals(secondSubjectCode)) {
                billDesc = "借款项目已投资满标，获得担保收益";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_FEE.getCode().equals(secondSubjectCode)) {
                billDesc = "您已担保该项目，支出保证金";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_OUTCOME.getCode().equals(secondSubjectCode)) {
                billDesc = "您已担保该项目，支出担保服务费";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_BACK_BAIL.getCode().equals(secondSubjectCode)) {
                billDesc = "项目流标或取消担保，退回保证金";
            } else if (BillSecondSubjectEnum.USER_GUARANTEE_SERVICE_FEE.getCode().equals(secondSubjectCode)) {
                billDesc = "项目流标或取消担保，退回担保服务费";
            }

            QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO userBillDetail = new QueryCreditRepaymentDynamicReponseVO.CreditRepaymentDynamicVO();
            userBillDetail.setSecondSubjectCode(secondSubjectCode);
            userBillDetail.setAmount(userBillResponseDTO.getAmount());
            userBillDetail.setStatusDesc(BillStatusEnum.getEnumByCode(userBillResponseDTO.getStatus()).getDesc());
            userBillDetail.setDescription(billDesc);
            userBillDetail.setCreateTime(DateUtils.formatDate(userBillResponseDTO.getCreateTime(), DateUtils.SHOW_DATETIME_FORMAT));
            return userBillDetail;
        }).collect(Collectors.toList());

        QueryCreditRepaymentDynamicReponseVO responseVO = new QueryCreditRepaymentDynamicReponseVO();
        responseVO.setProjectId(projectId);
        responseVO.setLastDescription(lastDescription);
        responseVO.setCreditRepaymentDynamicVOList(userBillDetailList);

        Long endTime = System.currentTimeMillis();
        log.info("queryCreditRepaymentDynamic end, cost:{} ms, request:{}, reponse:{}", endTime - startTime, JSON.toJSONString(request), JSON.toJSONString(responseVO));
        return Result.with(responseVO);
    }

    @PostMapping("/showCreditContract")
    @ApiOperation("提供信用借合同参数（赖春景）")
    public Result<CreditContractParmsResponseVO> getCreditContractParms(
            @RequestBody @Valid QueryCreditContractRequestVO requestVO) {

        String userId = PrincipalContext.getUserId();
        QueryCreditContractReponseDTO dto = creditDubboService.queryCreditContractParas(requestVO.getProjectId(),
                userId, requestVO.getType());
        CreditContractParmsResponseVO resultVo = new CreditContractParmsResponseVO();

        if (dto != null) {
            resultVo.setBorrowId(dto.getBorrowId());
            resultVo.setBorrowAmount(dto.getBorrowAmount());
            resultVo.setBorrowName(dto.getBorrowName());
            resultVo.setBorrowPlatformServiceFee(dto.getBorrowPlatformServiceFee());
            resultVo.setDeadline(dto.getDeadline());
            resultVo.setEffectiveDate(dto.getEffectiveDate());
            resultVo.setGuaranteeFee(dto.getGuaranteeFee());
            resultVo.setHorseFee(dto.getHorseFee());
            resultVo.setPenaltyRate(dto.getPenaltyRate());
            resultVo.setRefundDate(dto.getRefundDate());
            resultVo.setRepaymentType(dto.getRepaymentType());
            resultVo.setRepaymentTypeName(dto.getRepaymentTypeName());
            resultVo.setYearRate(dto.getYearRate());
            //投资人信息参数
            List<CreditContractParmsResponseVO.InvestUserVO> investList = new ArrayList<CreditContractParmsResponseVO.InvestUserVO>();
            List<InvestUserDTO> investInfoList = dto.getInvestUserList();
            for (InvestUserDTO investUserDTO : investInfoList) {
                CreditContractParmsResponseVO.InvestUserVO investUserVO = new CreditContractParmsResponseVO.InvestUserVO();
                investUserVO.setInvestId(investUserDTO.getInvestId());
                investUserVO.setInvestName(investUserDTO.getInvestName());
                investUserVO.setInvestAmount(investUserDTO.getInvestAmount());
                investList.add(investUserVO);
            }
            //担保人信息参数
            List<CreditContractParmsResponseVO.GuaranteeUserVO> guaranteeList = new ArrayList<>();
            List<GuaranteeUserDTO> guaranteeInfoList = dto.getGuaranteeUserList();
            for (GuaranteeUserDTO guaranteeUserDTO : guaranteeInfoList) {
                CreditContractParmsResponseVO.GuaranteeUserVO guaranteeUserVO = new CreditContractParmsResponseVO.GuaranteeUserVO();
                guaranteeUserVO.setGuaranteeId(guaranteeUserDTO.getGuaranteeId());
                guaranteeUserVO.setGuaranteeName(guaranteeUserDTO.getGuaranteeName());
                guaranteeUserVO.setGuaranteeOfRate(guaranteeUserDTO.getGuaranteeOfRate());
                guaranteeList.add(guaranteeUserVO);
            }

            resultVo.setInvestUserList(investList);
            resultVo.setGuaranteeUserList(guaranteeList);
            resultVo.setContractNo(dto.getContractNo() == null ? String.valueOf(requestVO.getProjectId()) : dto.getContractNo());
        }
        return with(resultVo);

    }

}